#include "bstnode.h"
#include <stdio.h>
#include <stdlib.h>
#include "string.h"

void bst_malloc_node(bst_node **node,int data)
{
    *node = (bst_node *)malloc(sizeof(bst_node));
    if(*node !=NULL)
    {
        (*node)->value = data;
        (*node)->left = NULL;
        (*node)->right = NULL;
    }

}

void bst_insert_node(bst_node **bstnode,int data)
{
    bst_node *bsttemp = *bstnode;
    if(bsttemp == NULL)
        bst_malloc_node(bstnode,data);
    else if(data >= bsttemp->value)
        bst_insert_node(&bsttemp->right,data);
    else
        bst_insert_node(&bsttemp->left,data);
}
void bst_print_node(bst_node *bstnode)
{
    if(bstnode !=NULL)
    {
        printf(" %d ,",bstnode->value);
      //  bst_print_node(bstnode->left);
        bst_print_node(bstnode->right);
    }

}

void bst_delete_node(bst_node **bstnode,int value)
{
    bst_node *temp = *bstnode;
    bst_node *maxnode = NULL;
    if(temp == NULL)
        printf("bst tree is not find node \n");
    else if(temp->value > value)
        bst_delete_node(&temp->left,value);
    else if((temp->value < value))
        bst_delete_node(&temp->right,value);
    else 
    {
        if(temp->right && temp->left)
        {
            maxnode = temp->left;
            while(maxnode->right != NULL)
                maxnode = maxnode->right;
            temp->value = maxnode->value;
            bst_delete_node(&temp->left,maxnode->value);
        }
        else    /*it is a leaft*/
        {
            *bstnode = temp->left;
            free(temp);

        }
    }

}
int main()
{
    bst_node *bsttree = NULL;
    bst_insert_node(&bsttree,20);
    bst_insert_node(&bsttree,5);
    bst_insert_node(&bsttree,4);
    bst_insert_node(&bsttree,29);
    bst_insert_node(&bsttree,11);
    bst_insert_node(&bsttree,7);
    bst_insert_node(&bsttree,12);
    bst_insert_node(&bsttree,10);
    bst_insert_node(&bsttree,9);
    bst_delete_node(&bsttree,11);
    bst_print_node(bsttree);
}